package model

import (
	"fmt"
	"gin_server/uitl"
	"gin_server/uitl/codemsg"
	"gin_server/uitl/response"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username string `json:"username" gorm:"type:varchar(20);not null " banding:"required,min=4,max=12" label:"用户名"`
	Password string `json:"password" gorm:"type:varchar(20);not null" banding:"required,min=6,max=20" label:"密码"`
	Role     int    `json:"role" gorm:"type:int;DEFAULT:2" banding:"required" label:"角色码"`
}

// IsUserModel查询用户是否存在
func IsUserModel(name string) int {
	var user User
	db.Select("id").Where("username = ?", name).First(&user)
	fmt.Println(user)
	if (user.ID) > 0 {
		return response.ERROR
	}
	return response.SUCCESS
}

// CreateUserModel新增用户
func CreateUserModel(data *User) int {
	data.Password = uitl.ScryptPw(data.Password)
	err := db.Create(&data).Error
	if err != nil {
		return response.ERROR
	}
	return response.SUCCESS
}

// GetUsersModel 查询用户
func GetUsersModel(pageSize int, pageNum int) []User {
	var users []User
	// 一页多pagesize个 有pageNum个(偏移量)
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil
	}
	return users
}

// 删除用户
func DeleteUserModel(id int) int {
	var user User
	err := db.Where("id = ?", id).Delete(&user).Error
	if err != nil {
		return codemsg.ERROR
	}
	return codemsg.SUCCESS
}

// UpdateUserModel 更新用户信息
func UpdateUserModel(id uint, data *User) int {
	userMap := map[string]interface{}{
		"username": data.Username,
		"role":     data.Role,
	}
	err := db.Model(&User{}).Where("id = ?", id).Updates(userMap).Error
	if err != nil {
		return codemsg.ERROR
	}
	return codemsg.SUCCESS
}

// 登陆
func LoginModel(username string, password string) int {
	var user User

	db.Where("username = ?", username).First(&user)
	if user.ID == 0 || uitl.ScryptPw(password) != user.Password {
		return response.ERROR
	}
	return response.SUCCESS
}
